package com.bsoft.core.serialization;

import java.io.*;

/**
 * jdk自带的序列化方式
 */
public class JDKSerialization implements Serialization {

    @Override
    public <T> byte[] serialize(T obj) {
        byte[] result = new byte[0];
        try (
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(bos);
        ) {
            oos.writeObject(obj);
            result = bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public <T> T deserialize(byte[] data, Class<T> clz) {
        T object = null;
        try (
                ByteArrayInputStream bis = new ByteArrayInputStream(data);
                ObjectInputStream ois = new ObjectInputStream(bis);
        ) {
            object = (T) ois.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return object;
    }
}
